<?php
// 应用公共文件

// 应用公共文件
use think\facade\Cache;
use think\facade\Request;
use think\Response;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Log;

function now()
{
    return date('Y-m-d H:i:s');
}

// 返回常用的api
function create($data = [], $msg = '请求成功', $code = 0, $type = 'json')
{
    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];
    return Response::create($result, $type);

}

// layui专用数据表格返回接口
function createTable($data = [], $msg = '请求成功', $count = 0, $code = 0, $type = 'json')
{
    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
        'count' => $count
    ];
    return Response::create($result, $type);

}

function upload_oss($tmp_name, $imgMime)
{
    try {
        $KeyId = config('filesystem.alioss.KeyId');
        $KeySecret = config('filesystem.alioss.KeySecret');
        $EndPoint = config('filesystem.alioss.endpoint');
        $Bucket = config('filesystem.alioss.bucket');
        //实例化
        $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
        //sha1加密 生成文件名 连接后缀
        $fileName = 'material' . '/' . date("Ym", time()) . '/' . date("d", time()) . "/" . sha1(date('YmdHis', time()) . uniqid()) . '.' . $imgMime;
        //执行阿里云上传
        $result = $ossClient->uploadFile($Bucket, $fileName, $tmp_name);
        //图片地址:$result['info']['url']
        $arr = ['code' => 0, 'msg' => '上传成功', 'url' => $result['info']['url'], 'local_url' => $tmp_name];
    } catch (OssException $e) {
        $arr = ['code' => 104, 'msg' => $e->getMessage(), 'data' => ''];
    }
    return $arr;
}

function getChildrenId($data, $pid)
{
    $arr = array();
    foreach ($data as $v) {
        if ($v['pid'] == $pid) {
            $arr[] = $v['id'];
            $arr = array_merge($arr, getChildrenId($data, $v['id']));
        }
    }
    return $arr;
}


if (!function_exists('upload_file')) {
    //上传图片
    function upload_file($files, $path = "./uploads", $imagesExt = ['jpg', 'png', 'jpeg', 'gif', 'mp4','mov','avi','xlsx','xls'])
    {
        // 判断错误号
        if (@$files['error'] == 00) {
            // 判断文件类型
            $ext = strtolower(pathinfo(@$files['name'], PATHINFO_EXTENSION));
            if (!in_array($ext, $imagesExt)) {
                return "非法文件类型";
            }
            // 判断是否存在上传到的目录
            // 生成唯一的文件名
            $fileName = md5(uniqid(microtime(true), true)) . '.' . $ext;

            // 将文件名拼接到指定的目录下
            $address = $path . "/images/" . date("Ym", time()) . '/' . date("d", time());
            $destName = $address . '/' . $fileName;
            // 进行文件移动
            if (!is_dir($address)) {
                mkdir($address, 0777, true);
            }
            if (!move_uploaded_file($files['tmp_name'], $destName)) {
                return "文件上传失败！";
            }
            return "uploads" . "/images/" . date("Ym", time()) . '/' . date("d", time()) . '/' . $fileName;
        } else {
            // 根据错误号返回提示信息
            switch (@$files['error']) {
                case 1:
                    throw new \think\Exception("上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值");
                case 2:
                    throw new \think\Exception("上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值");
                case 3:
                    throw new \think\Exception("文件只有部分被上传");
                case 4:
                    throw new \think\Exception("没有文件被上传");
                case 6:
                case 7:
                    throw new \think\Exception("系统错误");
            }
            return false;
        }
    }
}

function bubbling($array)
{
    $sort = array_column($array,'sort');
    array_multisort($sort,SORT_ASC,$array);
    return $array;
}

// 获取微信openid
function getWxOpenid($code)
{
    $header = array(
        'Accept: application/json',
    );
    $app_id = config('enum.app_id');
    $secret = config('enum.secret');
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/sns/jscode2session?appid='.$app_id.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code');
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 超时设置,以秒为单位
    curl_setopt($curl, CURLOPT_TIMEOUT, 1);

    // 超时设置，以毫秒为单位
    // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

    // 设置请求头
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    //执行命令
    $data = curl_exec($curl);
    curl_close($curl);
    return json_decode($data,true);
}

// curl封装get和post
function sCurl($url, $data = array(), $mode = 'GET')
{
    // 初始化
    $curl = curl_init();
    // 访问的URL
    curl_setopt($curl, CURLOPT_URL, $url);
    // 只获取页面内容，但不输出
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // 验证是否是https请求
    if (substr($url, 0, 5) == 'https'){
        // https请求，不验证证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // https请求，不验证HOST
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    if ($mode == 'POST'){
        // 设置请求方式为POST请求
        curl_setopt($curl, CURLOPT_POST, true);
        // POST请求数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    }
    // 执行CURL请求
    $result = curl_exec($curl);
    // 关闭curl，释放资源
    curl_close($curl);

    return $result;
}

if (!function_exists('priceFormat')) {
    function priceFormat($price)
    {
        return number_format($price/100,2);
    }
}

if (!function_exists('getDateDiff')) {
    function getDateDiff($date, $u_create_time)
    {
        $datetime1 = date_create($date);
        $datetime2 = date_create($u_create_time);
        $interval = date_diff($datetime2,$datetime1);
        return substr($interval->format('%R%a'),1);
    }
}

/**
 * 日志全局方法
 */
if (!function_exists('flog')) {
    /**
     * @param string $level //['error', 'warning', 'notice', 'info']
     */
    function flog($data, string $channel = 'flog', string $level = 'info'): bool
    {
        try {
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);

            if (is_array($data)) {
                $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            } elseif (is_object($data)) {
                $data = (array)$data;
            } else {
                //字符串或者数字
                $data = ['message' => $data];
            }

            $trace_info = $trace['0']['file'] . ' on line ' . $trace['0']['line'];

            if (isset($trace[1])) {
                $trace_info .= "\n" . $trace[1]['class'] . '::' . $trace[1]['function'];
            }

            $body = [
                'time' => now(),
                'body' => $data,
                'channel' => $channel,
                'level' => $level,
                'trace' => $trace_info,
            ];
            try {
                $module = app('http')->getName();
                if ($module){
                    $header = Request::header();
                    $redis = Cache::store('redis')->handler();
                    if ($module == 'api'){
                        $redis->select(8);
                        $body['user_id'] = $redis->get($header['token']) ?? 0;
                    }elseif ($module == 'h5'){
                        $redis->select(9);
                        $body['user_id'] = $redis->get($header['token']) ?? 0;
                    }elseif ($module == 'admin'){
                        $redis->select(3);
                        $tokenArr = json_decode($redis->get($header['token']),true);
                        $body['user_id'] = $tokenArr['user_id'] ?? 0;
                    }
                }
            }catch (Throwable $e){
            }

            Log::channel('flog')->log($level, json_encode($body));

            return true;
        } catch (Throwable $e) {

            Log::error($e->getMessage());

            return false;
        }
    }
}




